package controllers

import (
	"errors"
	"fmt"
	"github.com/beego/beego/v2/server/web"
	"log"
	"path"
	"quickConnect/models/globalValues"
	"regexp"
)

type UploadController struct {
	web.Controller
}

func (c *UploadController) Post() {
	key := c.GetString("key", "")
	if key != globalValues.Key {
		c.Ctx.ResponseWriter.WriteHeader(403)
		c.Ctx.WriteString("非法访问")
		c.StopRun()
	}
	aimPath := c.GetString("aim", "")
	aimPath = path.Join(globalValues.HomeDir, aimPath)
	pattern := "^" + globalValues.HomeDir + ".*$"
	ok, err := regexp.MatchString(pattern, aimPath)
	if err != nil {
		c.Ctx.WriteString(err.Error())
		c.StopRun()
	}
	if !ok {
		err := errors.New("目标目录超出用户目录，拒绝访问")
		log.Println(err.Error())
		c.Ctx.WriteString("fail")
		c.StopRun()
	}
	if err != nil {
		log.Println(err.Error())
		c.Ctx.WriteString("fail")
		c.StopRun()
	}
	fmt.Println(aimPath)
	_, fil, err := c.GetFile("file")
	err = c.SaveToFile("file", path.Join(aimPath, fil.Filename))
	if err != nil {
		log.Println(err.Error())
		c.Ctx.WriteString("fail")
		c.StopRun()
	}

	c.Ctx.WriteString("success")
}
